import CryptoJS from "crypto-js";
import config from "../config/wx";

const aid = config.config.aid;

function WXBizDataCrypt(aid, sessionKey) {
  this.aid = aid;
  this.sessionKey = sessionKey;
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // console.log("Received encryptedData:", encryptedData);
  // console.log("Received iv:", iv);

  // base64 decode
  var sessionKey = CryptoJS.enc.Base64.parse(this.sessionKey);
  encryptedData = CryptoJS.enc.Base64.parse(encryptedData);
  iv = CryptoJS.enc.Base64.parse(iv);

  // console.log("Parsed sessionKey:", sessionKey);
  // console.log("Parsed encryptedData:", encryptedData);
  // console.log("Parsed iv:", iv);

  try {
    // 解密
    var decipher = CryptoJS.algo.AES.createDecryptor(sessionKey, {
      iv: iv,
    });
    var decoded = decipher.process(encryptedData); // 使用 process 方法进行解密
    decoded.concat(decipher.finalize()); // 完成解密，将解密后的数据连接到 decoded

    decoded = JSON.parse(CryptoJS.enc.Utf8.stringify(decoded));

    // console.log("Decoded data:", decoded);
    // if (decoded.watermark.aid != this.aid) {
    //   console.error(
    //     decoded.watermark,
    //     "decoded.watermark.aid !==",
    //     this.aid
    //   );
    //   // throw new Error("Illegal Buffer");
    // }
  } catch (err) {
    console.error("Decryption error:", err);
    throw new Error("Illegal Buffer");
  }



  return decoded;
};




export default WXBizDataCrypt;
